package com.yonyou.le.unattended.websocket;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.google.gson.Gson;

/**
 * 功能说明：用来存储业务定义的sessionId和连接的对应关系,利用sessionId来消息的推送
 * 作者：zhangbbd
 */
public class MonitorUtils {

	public static Map<String,Map<String,WebSocketSession>> opMap = new ConcurrentHashMap<>();

	/**
	 * 添加作业点的一个session
	 * @param opCode
	 * @param session
	 */
	public static void putSession(String opCode, WebSocketSession session) {
		if(!opMap.containsKey(opCode)){
			opMap.put(opCode, new ConcurrentHashMap<String, WebSocketSession>());
		}
		opMap.get(opCode).put(session.getId(),session);		
	}

	public static Map<String,WebSocketSession> getSession(String opId) {
		return opMap.get(opId);
	}
	/**
	 * 根据session会话删除
	 * @param sessionId
	 */
	public static void removeBySession(String sessionId) {
		for(Map<String,WebSocketSession> ws:opMap.values()){
			ws.remove(sessionId);
		}
	}
	/**
	 * 根据作业点编码删除
	 * @param opcode
	 */
	public static void removeByOpcode(String opcode) {
		opMap.remove(opcode);
	}

	/**
	 * 判断是否有连接
	 * 
	 * @param sessionId
	 * @return boolean
	 */
	public static boolean hasConnection(String sessionId) {
		for(Map<String,WebSocketSession> ws:opMap.values()){
			if(ws.containsKey(sessionId)){
				return true;
			}
		}
		return false;
	}
	/**
	 * 发送消息给指定session
	 * @param opcode
	 * @param type
	 * @param data
	 * @throws IOException
	 */
	public static void sendMessage(String type,String opcode, String data) throws IOException {
		Map<String, WebSocketSession> session = MonitorUtils.getSession(opcode);
		if(session==null)return;
		Gson gson = new Gson();
		MonitorMsg sm = new MonitorMsg(type,opcode, data);
		for (WebSocketSession wss : session.values()) {
			if (wss.isOpen()) {
				wss.sendMessage(new TextMessage(gson.toJson(sm).getBytes("utf-8")));
			}
		}
		
	}
	

}
